<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPermissionAnchorModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserExtContractModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\OpenShop\StartBusiness\OpenShopStartBusinessModel;
use App\Service\Guanyuan\CurlService;
use App\Service\OpenShop\Feishu\MessageSendService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\Feishu\ShopManualService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\User\RmsUserService;
use App\Support\OrganizationManageFsRobotSendSupport;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;

class ModifyOrderSign extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'open_shop:modify-order {shopCode} {--staffCount=} {--monthlyWages=} {--fixedRent=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '手动修改开店订单数据 .';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private array $modifyStartField = [];

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $shopCode     = (int)$this->argument('shopCode');
        $staffCount   = $this->option('staffCount');
        $monthlyWages = $this->option('monthlyWages');
        $monthlyWages = $monthlyWages * 100;
        $fixedRent    = $this->option('fixedRent');
        $fixedRent    = $fixedRent * 100;


        $startField = [];
        // 开业字段
        $startFieldText = [
            'staffCount'   => '员工人数',
            'monthlyWages' => '总月工资',

        ];

        $locationsField     = [];
        $locationsFieldText = [
            'fixedRent' => '固定租金'
        ];


        if (!empty($staffCount)) {
            $startField['staffCount'] = $staffCount;
        }

        if (!empty($monthlyWages)) {
            $startField['monthlyWages'] = $monthlyWages;
        }

        if (!empty($fixedRent)) {
            $locationsField['fixedRent'] = $fixedRent;
        }

        $signOrder = OpenShopSignOrderModel::query()->with('baseInfoRel')->where('shopCode', $shopCode)
                                           ->where('status', '!=', 0)->first();
        if (empty($signOrder)) {
            $this->info('查无此订单 结束操作');
            return;
        }

        $effectRow = 0;
        // 开业报告修改
        $orgDateStart = OpenShopStartBusinessModel::query()->where('orderNo', $signOrder->orderNo)->first();
        if (!empty($startField)) {
            $effectRow += OpenShopStartBusinessModel::query()->where('orderNo', $signOrder->orderNo)->update(
                $startField
            );
        }


        // 选址数据修改
        $orgDateLocation = OpenShopSiteLocationModel::query()->where('orderNo', $signOrder->orderNo)->where('source', 0)
                                                    ->first();
        if (!empty($locationsField)) {
            $effectRow += OpenShopSiteLocationModel::query()->where('orderNo', $signOrder->orderNo)->where('source', 0)
                                                   ->update(
                                                       $locationsField
                                                   );
        }


        $provinceCode     = $signOrder->baseInfoRel->chooseShopCityCode;
        $organizationUser = OrganizationManageService::getProvinceInfoByProvinceCode($provinceCode);

        $organizationUser['operationUserFeishuId'] = '';
        if (!empty($organizationUser) && !empty($organizationUser['operationUid'])) {
            $operationUser = RmsUserService::getRmsUserInfoByUserIds($organizationUser['operationUid']);
            if ($operationUser['code'] == 200) {
                $organizationUser['operationUserFeishuId'] = $operationUser['data'][0]['feishuUserId'];
            }
        }

        // 飞书 强制通知人 - xm, 吉连, 风雪, 九月
        $fsSend = [
            '3fgc8798',
            '9efgbcdb',
            '9acce1b7',
            'c4dd5156',
        ];
        // 获取当前环境
        if (config('app.env') == 'prod' || config('app.env') == 'pre') {
            if (!empty($organizationUser['operationUserFeishuId'])) {
                $fsSend[] = $organizationUser['operationUserFeishuId']; // 添加省区总
            }
            $fsSend[] = 'fea66474'; // 巴斯
            $fsSend[] = '5dd87136'; // 山治
            $fsSend[] = 'Z000236'; // 烟柔
            $fsSend[] = 'e58f8774'; // 琴酒
        }

        // 手动设置成生产机器人
        Config::set('feishu.openShop.appID', 'cli_a29222d9e7fc900b');
        Config::set('feishu.openShop.AppSecret', 'pD3Xca1gqECIM1ULslsxAeznpo6eBNuo');

        $fs = new MessageSendService();
        $fs->setText('**开店订单修改通知**')
           ->setField('开店单号', $signOrder->orderNo)
           ->setField('门店编号', $signOrder->shopCode)
           ->setField('对应省总', $organizationUser['operationName'] ?? '暂无省区总')
           ->setField('修改字段如下', '↓');

        foreach ($startField as $key => $item) {
            $fs->setField($startFieldText[$key] ?? '', $orgDateStart->$key . ' => ' . $item);
        }

        foreach ($locationsField as $key => $item) {
            $fs->setField($locationsFieldText[$key] ?? '', $orgDateLocation->$key . ' => ' . $item);
        }

        $fs->setField('修改时间', date('Y-m-d H:i:s'))
           ->setReceiveFeiShuIds($fsSend)
           ->send();

        $this->info('更新成功, 影响行数' . $effectRow);

    }
}
